package com.gzy.rpsm_property.service.Impl;

import com.gzy.rpsm_property.mapper.AttentionMapper;
import com.gzy.rpsm_property.pojo.Attention;
import com.gzy.rpsm_property.pojo.ResponsePojo;
import com.gzy.rpsm_property.pojo.User;
import com.gzy.rpsm_property.pojo.Users;
import com.gzy.rpsm_property.service.AttentionService;
import com.gzy.rpsm_property.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class AttentionServiceImpl implements AttentionService {

    @Autowired
    private AttentionMapper attentionMapper;
    @Autowired
    private UserService userService;

//    @Override
//    public void addAttention(String fromUsername, String toUsername) {
//        attentionMapper.insertAttention(fromUsername, toUsername);
//    }
    @Override
    public List<Map<String, Object>> getAttentionList() {
        return attentionMapper.getAttentionList();
    }

    @Override
    public List<Users> getFollowingUsersByUsername(String username) {
        return attentionMapper.getFollowingUsersByUsername(username);
    }

    @Override
    public List<Users> getFollowersByUsername(String username) {
        return attentionMapper.getFollowersByUsername(username);
    }
    @Override
    public ResponsePojo<Void> followUser(String followerUsername, String followingUsername) {
        Optional<User> follower = userService.getUserByUsername(followerUsername);
        Optional<User> following = userService.getUserByUsername(followingUsername);

        if (!follower.isPresent() || !following.isPresent()) {
            return ResponsePojo.fail(null, "用户不存在");
        }

        int fromId = follower.get().getUserid();
        int toId = following.get().getUserid();

        if (attentionMapper.countExistingAttention(fromId, toId) > 0) {
            return ResponsePojo.fail(null, "已经关注过该用户");
        }

        Attention attention = new Attention();
        attention.setFromId(fromId);
        attention.setToId(toId);
        attention.setAttendDate(new Date(System.currentTimeMillis()));

        attentionMapper.insertAttention(attention);
        return ResponsePojo.success(null);
    }
}

